package com.oristartech.xxlconf.config;

import com.xxl.conf.core.XxlConfClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;

import java.nio.charset.StandardCharsets;

/**
 ** 配置工具类
 * 
 * @author chenfenghai
 * @date 2019/09/10
 */
@Slf4j
public class ConfigUtil {

    private ConfigUtil() {}

    /**
     ** 根据key获取配置值
     * 
     * @param key
     * @return
     */
    public static String getConfig(String key) {
        return getConfig(key, null);
    }

    /**
     ** 根据key获取配置值，没有则返回默认值
     * 
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getConfig(String key, String defaultValue) {
        String value = getRemoteConfig(key);
        if (StringUtils.isEmpty(value)) {
            value = getLocalConfig(key);
        }
        if (value == null && defaultValue != null) {
            value = defaultValue;
        }
        return value;
    }

    /**
     ** 获取本地配置值
     * 
     * @param key
     * @return
     */
    private static String getLocalConfig(String key) {
        try {
            Environment env = SpringContextHolder.getApplicationContext().getBean(Environment.class);
            // 解决中文乱码问题，property默认编码是ISO-8859-1，需要转换为UTF-8
            return new String(env.getProperty(key).getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("get local config[{}] error: {}", key, e);
        }
        return null;
    }

    /**
     ** 获取远程配置值
     * 
     * @param key
     * @return
     */
    private static String getRemoteConfig(String key) {
        try {
            return XxlConfClient.get(key);
        } catch (Exception e) {
            log.error("get remote config[{}] error: {}", key, e);
        }
        return null;
    }
}
